package TCPEchoServerAndSlient0407;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Description:
 * User:岁亮亮
 * Date:2025-04-07
 * TIME:21:03
 */
public class TcpEchoSlientDemo {

    //建立一个客户端的文件描述符表
    private Socket socket = null;

    public TcpEchoSlientDemo(String serverIP,int port) throws IOException {
        socket = new Socket(InetAddress.getByName(serverIP),port);
    }

    public void start(){
        System.out.println("客户端上线-> ");
        try(Scanner scannerConsole = new Scanner(System.in);
            Scanner scannerSocket = new Scanner(socket.getInputStream());
            PrintWriter writer = new PrintWriter(socket.getOutputStream())) {

            while(true){

                String request = scannerConsole.next();
                writer.println(request);
                writer.flush();
                String response = scannerSocket.next();
                System.out.printf("响应是 : %s",response);
                System.out.println();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static void main(String[] args) throws IOException {
        TcpEchoSlientDemo tcpEchoSlientDemo = new TcpEchoSlientDemo("127.0.0.1",9090);
        tcpEchoSlientDemo.start();
    }

}
